<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

</body>
<script>
    // 深度搜索
    {
        const tree = [
            {
                name: "数据1",
                id: 1,
                children: [
                    {
                        name: "数据2",
                        id: 2,
                        children: [
                            {
                                name: "数据3",
                                id: 3,
                                children: [
                                    {
                                        name: "数据4",
                                        id: 4,
                                        children: [],
                                    }
                                ],
                            },
                        ],
                    },
                ]
            }
        ]

        function getTreeNode1(id,tree){
            let node = null
            tree.forEach(item => {
                if (item.id === id){
                    node = item
                } else if(item.children.length > 0) {
                    node = getTreeNode(id,item.children)
                }
            })
            return node
        }

        console.log(getTreeNode1(5,tree))
    }

    // 广度搜索
    {
        const tree = [
            {
                name: "数据1",
                id: 1,
                children: [
                    {
                        name: "数据2",
                        id: 2,
                        children: [
                            {
                                name: "数据3",
                                id: 3,
                                children: [
                                    {
                                        name: "数据4",
                                        id: 4,
                                        children: [],
                                    }
                                ],
                            },
                        ],
                    },
                ]
            }
        ]
        function getTreeNode2(id,tree){
            let queue = [...tree]
            while (queue.length > 0){
                const node = queue.shift()
                if (node.id === id){
                    return node
                }
                if (node.children){
                    queue = [...queue,...node.children]
                }
            }
        }
        console.log(getTreeNode2(4,tree))
    }
</script>
</html>